<?php

namespace App\Admin\Forms;

use App\Clients\CrmClient;
use App\Models\Clue;
use App\Models\Media;
use App\Models\Project;
use App\Models\Tag;
use Dcat\Admin\Admin;
use Dcat\Admin\Form\Row;
use Dcat\Admin\Models\Administrator;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Alert;
use Dcat\Admin\Widgets\Form;
use Dcat\Admin\Contracts\LazyRenderable;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class ClueArchiveForm extends Form implements LazyRenderable
{
    use LazyWidget;

    // 使用异步加载功能
    const SEX_LIST = [
        1 => '男',
        2 => '女',
    ];

    const INCOME_LIST = [
        'IC_TEGAO' => '特高(10W以上)',
        "IC_LIANGHAO" => '高(3W以上)',
        "IC_YIBAN" => '中(1到3W)',
        "IC_CHA" => '低(1W以下)',
    ];

    // 处理请求
    public function handle(array $input)
    {
        // 获取外部传递参数

        $id = data_get($this->payload, 'id');
        if (!$id)
            return $this->response()->error("错误!无法识别到ID!");

        if (!data_get($input, 'MediaSourceType') || !data_get($input, 'MediaSource')) {
            return $this->response()->error("错误,无法识别该号码建档媒介,请联系运营,并提供线索号码");
        }

//        if (admin_setting('enable_clue_tags') && $tag = data_get($input, 'tag_id'))
//            Clue::query()->where('id', $id)->update([
//                'tag_id' => $tag
//            ]);

//        unset($input['tag_id']);
        $code = data_get($input, 'CreatedBy');
        $phone = data_get($input, 'Phone');
        if (!$code)
            return $this->response()->withValidation([
                '_CreatedBy' => "建档人不能为空,如果未配置CRM登录名请配置CRM登录名",
                'CreatedBy' => "建档人不能为空,如果未配置CRM登录名请配置CRM登录名"
            ]);
        $client = CrmClient::make();
        $userInfo = $client->getUserIdOfCode($code);
        if (!$userInfo['id'])
            return $this->response()->withValidation([
                'CreatedBy' => "无法检索到建档人,请检查建档人账号是否正确"
            ]);

        $input['CreatedBy'] = $userInfo['id'];
        $input['PlanRecallEmp'] = $userInfo['id'];
        $input['PlanRecallEmps'] = $userInfo['name'];

        $guestId = data_get($this->payload, 'ad_name', data_get($this->payload, 'url'));
        if (strlen($guestId) > 1781)
            $guestId = substr($guestId, 0, 1781);
        $input['GuestId'] = htmlspecialchars($guestId);
        $input['Remark'] = htmlspecialchars($input['Remark']);
        if (isset($input['WeixinNo']))
            $input['WeixinNo'] = htmlspecialchars($input['WeixinNo']);
        if (isset($input['Qq']))
            $input['Qq'] = htmlspecialchars($input['Qq']);

        $response = $client->ReservationTempCustInfoCreateApi($input);
        Log::debug("手动建档Debug $phone: ", $response);
        $a_status = $response['a_status'];
        if ($a_status) {
            if ($a_status === Clue::A_STATUS_ARCHIVE_ERROR) {
                Log::error('建档失败!!!!', [
                    'input' => $input,
                ]);
            }
            Clue::query()
                ->where('id', $id)
                ->update($response);

            $msg = $response['log'];
            return $this->response()
                ->successIf($a_status === 1, $msg)
                ->errorIf($a_status !== 1, $msg)
                ->refreshIf($a_status === 1);
        }
        Log::error('建档失败!!!!', [
            'input' => $input,
            'response' => $response,
        ]);
        return $this->response()->error('错误!');
    }

    public function form()
    {
        // 获取外部传递参数
        //$id = $this->payload['id'] ?? null;
        $this->row(function (Row $form) {
            $alert = new Alert("部分数据为自动生成,建档时甄别一下数据正确性,看到不对的,提出来以便改进机器学习");
            $form->html($alert);
            $form->width(6)->datetime('DatetimeReg', '建档时间')->required();
            if (\Admin::user()->isAdministrator())
                $form->width(6)->text('CreatedBy', '建档人(请填写CRM的登录账号,例如: 8081)')->required();
            else {
                $form->width(6)->display('CreatedBy', '建档人');
                $form->hidden('CreatedBy');
            }

            $form->width(4)->text('CustName', '顾客姓名')->required();
            if (\Admin::user()->isAdministrator())
                $form->width(4)->text('Phone', '顾客电话')->required();
            else {
                $form->width(4)->display('Phone', '顾客电话');
                $form->hidden('Phone');
            }

            $form->width(4)->number('Age', '年龄')->required();
            $form->hidden('Country', '国家')->default(0);

            $form->width(4)->select('Province', '省份')
                ->options(getProvince()->pluck('name', 'code'))
                ->load('City', admin_route("admin.api.city"))
                ->required();
            $form->width(4)
                ->select('City', '城市')
                ->load('Area', admin_route("admin.api.area"))
                ->required();
            $form->width(4)
                ->select('Area', '区域(可以不填)');
            $form->width(4)
                ->select('IncomeCapacity', '消费能力')
                ->options(self::INCOME_LIST)
                ->required();
            $form->width(4)
                ->select('Sex', '性别')
                ->options(self::SEX_LIST)
                ->required();
            $form->width(4)
                ->select('TmpCustRegType', '建档类型')
                ->options(Project::getCustomerList())
                ->required();

            if (Admin::user()->inRoles(['operator','administrator']) || !admin_setting('hidden_archive_source')) {
                $typeList = Media::getMediaType();
                $form->width(6)->select('MediaSourceType', '媒介类型')
                    ->options(collect($typeList)->pluck('name', 'key')->toArray())
                    ->required()
                    ->load('MediaSource', admin_route("admin.api.media.children"));
                $form->width(6)
                    ->select('MediaSource', '媒介来源')
                    ->required();
            } else {
                $form->hidden("MediaSourceType");
                $form->hidden("MediaSource");
            }

            if (admin_setting('display_wechat'))
                $form->width(6)->text('WeixinNo', '微信');

            if (admin_setting('display_qq'))
                $form->width(6)->text('Qq', 'QQ')->rules('max:80', [
                    'max' => '文字超过上限80个字符'
                ]);

            $form->width(12)
                ->textarea('Remark', '备注');
        });
    }

    // 返回表单数据，如不需要可以删除此方法
    public function default()
    {
        $clue = $this->payload;

        $p = Project::checkProject($clue);
        $m = Media::checkMedia($clue);
        return [
            'DatetimeReg' => now()->toDateTimeString(),
            'CustName' => data_get($this->payload, 'name') ?? '女士',
            'Phone' => data_get($this->payload, 'phone'),
//            'tag_id' => data_get($this->payload, 'tag_id'),
            'Sex' => 2,
            'Age' => 1,
            'Country' => '0',
            'Province' => admin_setting('Province', 610000),
            'City' => admin_setting('City', 610100),
            'Area' => admin_setting('Area', 610122),
            // 消费能力
            'IncomeCapacity' => 'IC_CHA',
            // 媒介 一
            'MediaSourceType' => data_get($m, 'crm_media_source_type'),
            // 媒介 二
            'MediaSource' => data_get($m, 'crm_media_source'),
            // 回访人名字
            'PlanRecallEmps' => 'IC_CHA',
            // 回访人
            'PlanRecallEmp' => 'IC_CHA',
            // 建档人
            'CreatedBy' => data_get($clue, 'user.crm_username', '999'),
            '_CreatedBy' => data_get($clue, 'user.crm_username', '999'),
            // 建档类型
            'TmpCustRegType' => data_get($p, 'customer_type'),
            'Remark' => admin_setting('comment_example', data_get($this->payload, 'remark')),
        ];
    }
}
